import { request } from '~/utils/http'
/**
 * 自动注入分页请求
 * @param  apiOrUri 要请求的地址或者apis中定义的方法 地址必须是自定义apis
 * @param  spread 是否对外提供默认的方法
 * @returns
 */
export function useList<T = any>(apiOrUri: string | ApiCall<T>, spread: boolean = true) {
  const tableData: TableData<T> = reactive({ meta: { page: 1, size: 10, total: 1 }, lists: [], extra: {} })

  const loadingList = ref(false)
  /**
   * 获取列表
   */
  const getList = async () => {
    if (tableData.extra.timeRange && tableData.extra.timeRange.length === 2) {
      tableData.extra.startTime = tableData.extra.timeRange[0]
      tableData.extra.endTime = tableData.extra.timeRange[1]
    }
    const param = { page: tableData.meta.page, size: tableData.meta.size, ...tableData.extra }

    let data = {} as ResPage<T>
    if (apiOrUri instanceof String) {
      const uri = apiOrUri as string
      data = await request(uri, param).loading(loadingList).success<ResPage<T>>()
    } else {
      const req = apiOrUri as Function
      data = await req(param, loadingList)
    }

    tableData.lists = data.lists
    tableData.meta = data.meta
  }

  const changePage = (page: number) => {
    tableData.meta.page = page
    getList()
  }

  const resetList = (cleanExtra: boolean, filter: any) => {
    tableData.lists = []
    tableData.meta = { page: 1, size: 10, total: 1 }
    if (cleanExtra) {
      if (filter != null) {
        tableData.extra = filter
      } else {
        tableData.extra = {}
      }
    }
  }
  if (spread) {
    provide('tableData', tableData)
    provide('getList', getList)
    provide('changePage', changePage)
    provide('resetList', resetList)
  }

  return {
    loadingList,
    tableData,
    getList,
    changePage,
    resetList
  }
}
